{% extends "base.html" %}

{% block content %}
<script language="JavaScript" src="{{ MEDIA_URL }}js/jquery.min.js"></script>
<script language="JavaScript" src="{{ MEDIA_URL }}js/render.js"></script>
<script language="JavaScript" src="{{ MEDIA_URL }}js/chtextarea.js"></script>
<script type="text/javascript">//<![CDATA[
function format_date(year, month, date, hour, min, sec) {
  return year + ("-0" + month + "-0" + date + " 0" + hour + ":0" + min + ":0" + sec).replace(/0(\d\d)/g, "$1");
}

function ajax_save() {
  base_url = '{% url djambe.wiki.views.ajax_save id %}';
  id = $('#page_id').html();
  save_url = base_url.replace(/\/\d+\/$/, '/' + id + '/');

  fill_title();

  tag_text = '';
  $("[name='tags']").each(
    function(i) {
      if($(this).is(":checked")) {
        tag_text = tag_text + $(this).val() + ',';
      }
    }
  )
  tag_text = tag_text.replace(/,$/, '');

  $.post(
    save_url,
    {
      'title': $('#id_title').val(),
      'text': $('#id_text').val(),
      'is_public': $("#id_is_public option:selected").val(),
      'is_editable': $("#id_is_editable option:selected").val(),
      'tag_text': tag_text,
      'new_tag1': $('#id_new_tag1').val(),
      'new_tag2': $('#id_new_tag2').val(),
      'new_tag3': $('#id_new_tag3').val()
    },
    function(result, status) {
      if(id == 0) {
        document.edit_form.action = document.edit_form.action.replace(/\/0\/$/, '/' + result['id'] + '/');
      }
      $('#page_id').html(result['id']);
      d = new Date();
      $('#edit_result').html(result['message'] + ' at ' + format_date(d.getFullYear(), d.getMonth() + 1, d.getDate(), d.getHours(), d.getMinutes(), d.getSeconds()));
    },
    'json'
  );
}

function fill_title() {
  if($('#id_title').val() == '') {
    title_len = $('#id_text').val().replace(/\r\n/g, "\n").replace(/\r/g, "\n").indexOf("\n");
    if(title_len == -1) {
      title_len = $('#id_text').val().length;
    }
    $('#id_title').val($('#id_text').val().substr(0, title_len).replace(/\*/g, ''));
  }
}

function submit_form() {
  fill_title();
  AJAX_UNLOCK = false;
  document.edit_form.submit();
}

function confirm_quit() {
  if(window.confirm('Are you sure to quit without saving?')){
    AJAX_UNLOCK = false;
    location.href = '{% url djambe.wiki.views.quit_editing id %}';
  }
  else {
    alert('Quit canceled');
  }
}

function preview() {
  document.getElementById('preview').style.display = 'block';
  document.getElementById('preview').innerHTML = wikify(document.getElementById('id_text').value);
}

addEvent(window, 'load', function() {
    var elm = document.getElementById('id_text');
    var obj = ElementResizer.add(elm);
    var cursor = false;
    addEvent(elm, 'mousemove', function(e) {
        if(!cursor && obj.resizePoint(e)) {
          elm.style.cursor = 's-resize';
          cursor = true;
        }
        else if(cursor && !obj.resizePoint(e)) {
          elm.style.cursor = 'default';
          cursor = false;
        }
      }
    );
  
    ElementResizer.start();
  }
);


var AJAX_UNLOCK = true;
addEvent(window, 'unload', function() {
    id = $('#page_id').html();
    if(AJAX_UNLOCK && id > 0) {
      var unlock_url = '{% url djambe.wiki.views.ajax_unlock id %}';
      $.ajax({
        type: 'GET',
        url: unlock_url,
        success: function(result) {
            if(result['result'] != 'Success') {
              alert('Unlock failed.');
            }
          },
        error: function() {
            alert('Unlock failed.');
          },
        dataType: 'json',
        async: false
      });
    }
  }
);


// http://homepage3.moe-nifty.com/lifelicene/2011/02/javascript-ctrl.html
window.document.onkeydown = keys;

function keys(eve) {
  var winjudge = false;
  if(eve == null){
    eve = window.event;
    winjudge = true;
  }
  var keyCode = eve.which ? eve.which : eve.keyCode;
  switch (keyCode) {
    case 116: // F5
      if(winjudge) eve.keyCode = 0;
      return false;
    case 82: // Ctrl + R
      if(eve.ctrlKey) {
        if(winjudge) eve.keyCode = 0;
        return false;
      }
      break;
  }
}


//]]>
</script>
<h1>{{ instruction }}</h1>{{ errors|safe }}
<div id="page_id" style="display:none">{{ id }}</div><div id="preview" style="display:none"></div>
<form method="POST" name="edit_form" id="edit_form" action="{% url djambe.wiki.views.save id %}">
  <table style="width:98%" class="edit">
    {{ form }}
  </table>
</form>
<input type="button" onclick="submit_form()" value="Save and quit editing"><br/>
<input type="button" onclick="ajax_save()" value="Save and continue editing"><span id="edit_result" style="margin-left:10px"></span><br/>
<input type="button" onclick="preview()" value="Preview"><br/>
<input type="button" onclick="confirm_quit()" value="Quit editing without saving">
{% ifequal instruction 'Edit Page' %}
<br/><input type="button" onclick="window.location.href='{% url djambe.wiki.views.delete_confirm id %}'" value="Delete this page">
{% endifequal %}
{% endblock %}